﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class RZPlayerControl : MonoBehaviour
{
    // 设置距离
    [SerializeField] private float distance;
    [SerializeField] private float speedTime;

    [SerializeField] private Transform tongueTip;
    [SerializeField] private LineRenderer lr;
    [SerializeField] private RZDropPoint dpCtrl;
    [SerializeField] private LayerMask whatIsGrappleable;
    private Transform grapple;
    private Rigidbody2D rigid;

    [HideInInspector] public bool isDrop = false;

    bool isJump = false;

    private void Awake ()
    {
        rigid = gameObject.GetComponent<Rigidbody2D> ();
        lr.enabled = false;
    }

    private void Update ()
    {
        if (Input.GetKeyUp(KeyCode.E) && isDrop && !isJump)
        {
            isJump = true;
            lr.enabled = true;
            rigid.simulated = false;
        }

        if (isJump)
        {
            MoveGrapple ();
        }
        else
        {
            JudgeDropChild ();
        }

    }

    int cnt = -1;

    void JudgeDropChild ()
    {
        for (int i = 0;i < dpCtrl.childs.Count;i++)
        {
            if(!Jugde.Contain (transform.position.y, dpCtrl.childs[i].child.position.y))
            {
                Debug.Log ($"{i} Contain = false");
                dpCtrl.childs[i].RestoreColor ();
                continue;
            }

            // 射线
            if (!dpCtrl.childs[i].IsShield(transform.position, whatIsGrappleable))
            {
                Debug.Log ($"{i} IsShield = false");
                dpCtrl.childs[i].RestoreColor ();
                continue;
            }

            if (dpCtrl.childs[i].GetDist (transform.position, distance))
            {
                cnt = i;
                grapple = dpCtrl.childs[i].child;
                dpCtrl.childs[i].ChangeColor ();
                break;
            }
        }

        if (cnt >= 0)
        {
            isDrop = true;
        }
    }

    // 跳跃
    void MoveGrapple ()
    {
        transform.DOMove (grapple.position, speedTime);
        DrawRope ();

        if (Jugde.Contain (grapple.position, transform.position))
        {
            isJump = false;
            isDrop = false;
            lr.enabled = false;
            grapple = null;
            dpCtrl.childs[cnt].RestoreColor ();
            cnt = -1;
            rigid.simulated = true;
        }
    }
    // 画线
    void DrawRope ()
    {
        lr.SetPosition (index: 0, tongueTip.position); // 舌头 到 目的地
        lr.SetPosition (index: 1, new Vector3 (grapple.position.x, grapple.position.y, transform.position.z));
    }
}
